﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using Microsoft.Maps.MapControl;
using Microsoft.SharePoint.Client;

namespace Twitter_Map_Web_Part
{
    public partial class MainPage
    {
        public string BingMapsCredential { get; set; }

        ListItemCollection _tweets;
        private DispatcherTimer _timer;
        private int _currentTweetIndex;

        public MainPage()
        {
            InitializeComponent();
            Loaded += MainPage_Loaded;
        }

        public MainPage(string BingMapsKey)
        {
            InitializeComponent();
            BingMapsCredential = BingMapsKey;
            if (string.IsNullOrEmpty(BingMapsCredential)) throw new Exception("There is no map credential configured");
            TweetMap.CredentialsProvider = new ApplicationIdCredentialsProvider(BingMapsCredential);
            Loaded += MainPage_Loaded;
        }

        /// <summary>Page loaded event handler</summary>
        private void MainPage_Loaded(object Sender, RoutedEventArgs Args)
        {
            TweetText.Content = "Loading tweets ...";
            LoadListData(true);
        }

        private void LoadListData(bool RunSuccessMethod)
        {
            var context = ClientContext.Current;

            // get a reference to the current web
            var web = context.Web;

            //get a reference to the list that contains locations
            var tweetList = web.Lists.GetByTitle("Office Launch Tweets");

            //we need to obtain all items in the location list.     
            var query = new CamlQuery { ViewXml = "<View><Query><OrderBy><FieldRef Name='Tweet Time' Ascending='FALSE' IncludeTimeValue='FALSE' /></OrderBy></Query><RowLimit>7</RowLimit></View>" };
            _tweets = tweetList.GetItems(query);

            //batch up the work to perform
            context.Load(tweetList);
            context.Load(_tweets);

            if (RunSuccessMethod)
                context.ExecuteQueryAsync(ClientRequestSucceeded, ClientRequestFailed);
            else
                context.ExecuteQueryAsync(null, ClientRequestFailed);
        }

        /// <summary>
        /// Event handler for get request succeeded
        /// </summary>
        private void ClientRequestSucceeded(object Sender, ClientRequestSucceededEventArgs Args)
        {
            //execute the code in the UI thread as a anonymous method
            Dispatcher.BeginInvoke(() =>
            {
                try
                {
                    _timer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(8)};
                    _timer.Tick += TimerTick;
                    _timer.Start();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("ERROR");
                    MessageBox.Show(ex.ToString());
                }
            });
        }

        private void TimerTick(object Sender, EventArgs E)
        {
            TweetMap.Children.Clear();

            if (_currentTweetIndex == _tweets.Count)
            {
                TweetTitle.Content = null;
                TweetText.Content = "Checking for new tweets ...";
                TweetImage.Source = null;

                LoadListData(false);
                _currentTweetIndex = 0;
            }

            var tweet = _tweets[_currentTweetIndex];
            TweetTitle.Content = tweet["Tweet Author"].ToString();
            TweetText.Content = new TextBlock { Text = tweet["Title"].ToString(), 
                                                TextWrapping = TextWrapping.Wrap,
                                                Width = 450};
            var urlValue = tweet["Tweet Author Image"] as FieldUrlValue;
            if (urlValue != null) TweetImage.Source = new BitmapImage(new Uri(urlValue.Url));

            var loc = GetTweetLocation(tweet["Title"].ToString());
            TweetMap.Children.Add(new Pushpin { Location = loc });
            TweetMap.Center = loc;

            _currentTweetIndex++;
        }

        private static Location GetTweetLocation(string TweetContent)
        {
            if (TweetContent.ToUpper().Contains("#CBR"))
                return new Location(-35.28204, 149.12858);
            if (TweetContent.ToUpper().Contains("#MLB"))
                return new Location(-37.814251, 144.963169);
            if (TweetContent.ToUpper().Contains("#SYD"))
                return new Location(-33.867139, 151.207114);
            if (TweetContent.ToUpper().Contains("#BRI"))
                return new Location(-27.46758, 153.027892);
            if (TweetContent.ToUpper().Contains("#ADL"))
                return new Location(-34.92577, 138.599732);
            if (TweetContent.ToUpper().Contains("#DRW"))
                return new Location(-12.461334, 130.841904);
            if (TweetContent.ToUpper().Contains("#PER"))
                return new Location(-31.9554, 115.85859);
            if (TweetContent.ToUpper().Contains("#AUK"))
                return new Location(-36.847385, 174.765735);
            if (TweetContent.ToUpper().Contains("#CHC"))
                return new Location(-43.58039085560784, 172.6171875);
            if (TweetContent.ToUpper().Contains("#WLG"))
                return new Location(-41.310823880918186, 174.814453125);


            return new Location(-26.9416595453815, 132.9345703125);
            
        }

        /// <summary>
        /// Event handler for get request failed
        /// </summary>
        private void ClientRequestFailed(object Sender, ClientRequestFailedEventArgs Args)
        {
            //execute the code in the UI thread as a anonymous method
            Dispatcher.BeginInvoke(() => MessageBox.Show(string.Format("Error occured in displaying tweet locations:  {0}", Args.Message)));
        }
    }
}
